package com.appspot.modutajataja;

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.appspot.domain.RankVO;

public class MainActivity extends Activity {
	Animation ani;
	Intent intent;

	Button button_game;
	Button button_event;
	Button button_option;

	private MyAdapter adapter;
	private FirstAdapter adapter_first;
	private ListView listView;
	private ProgressDialog dialog;

	private Typeface font;
	private String userId;
	private String eventId;

	ArrayList<RankVO> rankList = new ArrayList<RankVO>();
	ArrayList<String> rankFirst = new ArrayList<String>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		userId = getIntent().getStringExtra("userId");

		new rankSelect(this).execute();

		button_game = (Button) findViewById(R.id.button_game);
		button_game.setOnClickListener(new MyHandler());
		button_event = (Button) findViewById(R.id.button_event);
		button_event.setOnClickListener(new MyHandler());
		button_option = (Button) findViewById(R.id.button_option);
		button_option.setOnClickListener(new MyHandler());

		TextView event_time = (TextView) findViewById(R.id.text_event_time);
		Calendar now = Calendar.getInstance();
		event_time.setText("EVENT 종료 시간 : "
				+ (23 - now.get(Calendar.HOUR_OF_DAY)) + "시간 "
				+ (60 - now.get(Calendar.MINUTE)) + "분");

		adapter = new MyAdapter(this);
		adapter_first = new FirstAdapter(this);
		rankFirst.add("랭킹 정보가 없습니다 게임에 도전하세요!");

		listView = (ListView) findViewById(R.id.main_ListView);
		listView.setDivider(null);
	} // end of onCreate method

	class MyHandler implements OnClickListener {
		Handler handler = new Handler();

		@Override
		public void onClick(View v) {

			if (v.getId() == R.id.button_game) {
				ani = AnimationUtils.loadAnimation(MainActivity.this, R.anim.scale);
				button_game.setEnabled(false);
				handler.postDelayed(new splashhandler(), 1000);
				startActivity(new Intent(MainActivity.this, GameActivity.class)
						.putExtra("userId", userId).putExtra("eventId", eventId));
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				finish();
			} else if (v.getId() == R.id.button_event) {
				button_event.setEnabled(false);
				handler.postDelayed(new splashhandler(), 1000);
				startActivity(new Intent(MainActivity.this, EventActivity.class)
						.putExtra("userId", userId).putExtra("eventId", eventId));
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				finish();
			} else if (v.getId() == R.id.button_option) {
				button_option.setEnabled(false);
				handler.postDelayed(new splashhandler(), 1000);
				startActivity(intent = new Intent(MainActivity.this,
						OptionActivity.class).putExtra("userId", userId).putExtra("eventId", eventId));
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				finish();
			}
		}
	} // end of MyHandler Class

	class splashhandler implements Runnable {
		public void run() {
			button_game.setEnabled(true);
			button_event.setEnabled(true);
			button_option.setEnabled(true);
		}
	}

	// adapter Class
	class MyAdapter extends ArrayAdapter {
		Context mc;

		public MyAdapter(Context context) {
			super(context, R.layout.list_item, rankList);
			mc = context;
		}

		@Override
		public int getCount() {
			return rankList.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			font = Typeface.createFromAsset(getAssets(), "fonts/cartoonist.ttf");

			LayoutInflater inflater = (LayoutInflater) mc.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View root = inflater.inflate(R.layout.list_item, null);
			TextView rank = (TextView) root.findViewById(R.id.list_no);
			rank.setTypeface(font);
			rank.setText(rankList.get(position).getNo() + "");

			TextView user_name = (TextView) root.findViewById(R.id.list_username);
			user_name.setTypeface(font);
			user_name.setSingleLine(true);
			user_name.setEllipsize(TruncateAt.MARQUEE);
			user_name.setSelected(true);
			user_name.setText(rankList.get(position).getUserId());

			TextView user_record = (TextView) root.findViewById(R.id.list_timerecord);
			user_record.setTypeface(font);
			long time = rankList.get(position).getGameTime();
			user_record.setText(String.format("%02d : %02d : %02d",
					time / 1000 / 60, (time / 1000) % 60, (time % 1000) / 10));

			ImageView win_image = (ImageView) root.findViewById(R.id.list_success_image);

			if (rankList.get(position).getNo() <= rankList.get(position).getGiftQty()) {
				win_image.setVisibility(View.VISIBLE);
			}
			return root;
		} // end of getView method
	} // end of MyAdapter class

	// first adapter Class
	class FirstAdapter extends ArrayAdapter {
		Context mc;

		public FirstAdapter(Context context) {
			super(context, R.layout.list_item_first, rankFirst);
			mc = context;
		}

		@Override
		public int getCount() {
			return rankFirst.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) mc.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View root = inflater.inflate(R.layout.list_item_first, null);
			TextView text_info = (TextView) root.findViewById(R.id.list_textinfo);
			text_info.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/cartoonist.ttf"));
			text_info.setText(rankFirst.get(0));
			return root;
		} // end of getView method
	} // end of FirstAdapter class

	class rankSelect extends AsyncTask<Void, Void, Void> {
		Context mc;

		public rankSelect(Context context) {
			this.mc = context;
			dialog = new ProgressDialog(mc);
		}

		@Override
		protected void onPreExecute() {
			dialog.setMessage("<랭킹정보 로딩중.....>");
			dialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				HttpClient client = new DefaultHttpClient();

				HttpGet get = new HttpGet(C.getRankListURL);

				HttpResponse response = client.execute(get);
				HttpEntity entity = response.getEntity();

				XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
				parser.setInput(new InputStreamReader(entity.getContent()));

				RankVO rank = new RankVO();
				while (parser.next() != XmlPullParser.END_DOCUMENT) {
					String name = parser.getName();
					if (name != null && name.equals("no")) {
						rank.setNo(Integer.parseInt(parser.nextText()));
					} else if (name != null && name.equals("userId")) {
						rank.setUserId(parser.nextText());
					} else if (name != null && name.equals("gameTime")) {
						rank.setGameTime(Long.parseLong(parser.nextText()));
					} else if (name != null && name.equals("giftQty")) {
						rank.setGiftQty(Integer.parseInt(parser.nextText()));
						rankList.add(rank);
						rank = new RankVO();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			dialog.dismiss();
			if (rankList.size() != 0) {
				listView.setAdapter(adapter);
			} else {
				listView.setAdapter(adapter_first);
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		WebView webView = (WebView) findViewById(R.id.main_WebView);
		webView.getSettings().setRenderPriority(RenderPriority.HIGH);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.loadUrl(C.tajaAppNewsURL);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	public void onBackPressed() {

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setMessage("게임을 종료 하시겠습니까?")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								finish();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = alt_bld.create();
		alert.setTitle("게임 종료");
		alert.setIcon(R.drawable.ic_launcher);
		alert.show();
	}
}; // end of MainActivity class